package com.zy.chat.chatai;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class ChatGptClient {
    private static final String API_KEY = "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";
    private static final String API_URL = "https://api.openai.com/v1/engines/davinci-codex/completions";

    private CloseableHttpClient httpClient;

    public  ChatGptClient() {
        this.httpClient = HttpClientBuilder.create().build();
    }

    public String getCompletion(String prompt) throws IOException {
        HttpPost httpPost = new HttpPost(API_URL);

        httpPost.addHeader("Authorization", "Bearer " + API_KEY);
        httpPost.addHeader("Content-Type", "application/json");

        String json = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": 1000, \"temperature\": 0.5}";

        httpPost.setEntity(new StringEntity(json));

        CloseableHttpResponse response = httpClient.execute(httpPost);
        String responseBody = EntityUtils.toString(response.getEntity());

        return responseBody;
    }
}
